﻿using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace BasicGridCollisionDemo
{
    public class CellObject : IGameObject
    {
        private readonly int _id;

        public int Id
        {
            get { return _id; }
        }

        public Vector2 Position { get; private set; }
        public Vector2 Size { get; private set; }
        public Color Color { get; private set; }

        public readonly Grid Grid;
        public readonly List<int> CellNums;

        public RectangleF BoundingRectangle;

        public CellObject( int id, Grid grid, Vector2  position, Vector2 size, Color color)
        {
            _id = id;
            Position = position;
            Size = size;
            Color = color;

            Grid = grid;

            CellNums = new List<int>();

            BoundingRectangle = new RectangleF(Position.X, Position.Y, Size.X, Size.Y);
        }

        public void ClearCellNumbers()
        {
            CellNums.Clear();
        }

        public void Move(Vector2 amount)
        {
            Position += amount;


            float x = Position.X;
            float y = Position.Y;

            if (x < 0)
                x = 0;
            else if (x + Size.X > Grid.CellWidth * Grid.NColumns -1)
                x = Grid.CellWidth*Grid.NColumns - Size.X -1;

            if (y < 0)
                y = 0;
            else if (y + Size.Y > Grid.CellHeight * Grid.NLines -1)
                y = Grid.CellHeight * Grid.NLines - Size.Y -1;


           Position = new Vector2(x, y);
           BoundingRectangle = new RectangleF(Position.X, Position.Y, Size.X, Size.Y);

           Grid.UpdateObject(this);
        }

        public void ChangeSize(Vector2 amount)
        {
            Size += amount;


            float x = Size.X > 0 ? Size.X : 1;

            float y = Size.Y > 0 ? Size.Y : 1;

            
            if (Position.X + Size.X > Grid.CellWidth * Grid.NColumns - 1)
                x = Grid.CellWidth * Grid.NColumns - Position.X - 1;

            
            if (Position.Y + Size.Y > Grid.CellHeight * Grid.NLines - 1)
                y = Grid.CellHeight * Grid.NLines - Position.Y - 1;

            Size = new Vector2(x, y);
            
            BoundingRectangle = new RectangleF(Position.X, Position.Y, Size.X, Size.Y);
        }



        public void Draw(SpriteBatch spriteBatch, GameTime gameTime, Texture2D blackTexture)
        {
            spriteBatch.Draw(blackTexture, BoundingRectangle, Color);
        }
    }
}
